package com.ht.common.core.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileConvertBase64 {
	protected final static Logger log = LoggerFactory.getLogger(FileConvertBase64.class);

    
    
	/**
	   * @param data base64 编码字符串
	   * @param path 文件存储路径
	   * @Description: 将base64编码字符串转成文件存储到制定，目录下
	   * @Author:
	   * @CreateTime:
	   */
	  public static  boolean generateFile(String data, String path) {
		    if (data == null) {
		      return false;
		    }
		    OutputStream out=null;
		    try {
		    	
		    byte[] b = Base64.getDecoder().decode(data);
		      mkdir(path);
		      log.info("输出未文件："+path);
		      out= new FileOutputStream(path);
		      out.write(b);
		      out.flush();
		      return true;
		    } catch (Exception e) {
		      return false;
		    }finally {
		    	if(null!=out) {
		    		try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
		    	}
		    }
		  }

	private static void mkdir(String path) {
		String dir=path.substring(0,path.lastIndexOf("/"));
		File file=new File(dir);
		if(!file.exists()) {
			 log.info("新建目录："+dir);
			file.mkdirs();
		}
	}
    /**
     * 将文件输入流转为base64
     */
        public static String getBase64FromInputStream(InputStream in) {
            // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
            byte[] data = null;
            // 读取图片字节数组
            try {
                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                while ((rc = in.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                data = swapStream.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return Base64.getEncoder().encodeToString(data);
        }
}
